<?php
class PagesController extends AppController {
	
	var $name = 'Pages';
	var $uses = array('Category', 'Location', 'Listing');
	
	// 86400 = 24 chasa | 864000 = 10 dena | 2592000 = 30 dena | 31536000 = 365 dena | 157680000 = 5 godini
	var $cacheAction = array(
 		'home' => '157680000'
 	);
	
	/**
	 * Category Model
	 *
	 * @var Category
	 */
	var $Category;
	
	/**
	 * Location Model
	 *
	 * @var Location
	 */
	var $Location;
	
	/**
	 * Tyk zadavame spisaka na action-ite s publichen dostyp (action-ite bez authorizaciq)
	 */
	function __initPublicActions() {
		$this->Auth->allow(array(
			'init_db',
			'display',
			'home',
		));
	}
	
	function beforeFilter() {
		parent::beforeFilter();
		
		$this->__initPublicActions();
	}
	
	function display() {
		$path = func_get_args();

		$count = count($path);
		if (!$count) {
			$this->redirect('/');
		}
		$page = $subpage = $title_for_layout = null;

		if (!empty($path[0])) {
			$page = $path[0];
		}
		if (!empty($path[1])) {
			$subpage = $path[1];
		}
		if (!empty($path[$count - 1])) {
			$title_for_layout = Inflector::humanize($path[$count - 1]);
		}
		$this->set(compact('page', 'subpage', 'title_for_layout'));
		$this->render(implode('/', $path));
	}
	
    function init_db() {
    	$this->loadModel('Group');
    	
    	$group =& $this->Group;
    	
    	//------------- root [id=1]
    	$group->id = 1;
    	
    	$this->Acl->allow($group, 'controllers');
    	//------------/ root [id=1]
    	
    	//------------- user [id=2]
    	$group->id = 2;
    	
    	$this->Acl->allow($group, 'controllers/Pages/display');
    	$this->Acl->allow($group, 'controllers/Pages/home');
    	//------------/ user [id=2]
    	
    	echo "all done";
    	exit;
    }
	
    private function getRootParentLocation($location_id){
      $root = $this->Location->getPath($location_id);
      if (count($root) > 0)
        return $root[0]['Location']['id'];
        
      return $location_id;
    }
    
    private function getRootParentCategory($category_id){
      $root = $this->Category->getPath($category_id);
      if (count($root) > 0)
        return $root[0]['Category']['id'];
        
      return $category_id;
    }
     
    function home() {		$this->layout= 'newdefault';
    	//================================ meta_info_for_layout
    	$meta_info_for_layout['head_title'] = 'Бизнес каталог с фирми';
    	$meta_info_for_layout['meta_description'] = 'Site Focus е български бизнес каталог с фирми.За да добавите вашата фирма безплатно в нашата директория,отидете на страницата Добави сайт';
    	$meta_info_for_layout['meta_keywords'] = 'бизнес директория,олайн каталог с фирми,';
    	
    	$this->set('meta_info_for_layout', $meta_info_for_layout);
    	//===============================/ meta_info_for_layout
      
      
      $showEmptyLocations = $this->Location->find('list', array(
        'recursive' => 0,
        'fields' => array('Location.id'),
        'conditions' => array('Location.is_showempty' => 1, 'Location.is_active' => 1)
      ));
      
      $haveListingLocations = $this->Listing->find('list', array(
        'recursive' => 0,
        'fields' => array('Listing.location_id'),
        'conditions' => array('Listing.is_active' => 1)
      ));            
      
      $location_ids = array();
      foreach($showEmptyLocations as $k => $v){
        $location_ids[] = $this->getRootParentLocation($v);
      }
      
      foreach($haveListingLocations as $k => $v){
        $location_ids[] = $this->getRootParentLocation($v);
      }
    
      $locations = $this->Location->find('all', array(
        'recursive' => 0,
        'conditions' => array('Location.id' => $location_ids, 'Location.is_active' => 1),
        'order' => 'Location.name ASC'
      ));
      
      $haveListingCategories = $this->Listing->find('list', array(
        'recursive' => 0,
        'fields' => array('Listing.category_id'),
        'conditions' => array('Listing.is_active' => 1)
      ));
      
      $category_ids = array();
      foreach($haveListingCategories as $k => $v){
        $category_ids[] = $this->getRootParentCategory($v);
      }
      
      $categories = $this->Category->find('all', array(
        'recursive' => 0,
        'conditions' => array('Category.id' => $category_ids, 'Category.is_active' => 1),
        'order' => 'Category.name ASC'
      ));
      
      $this->set(compact('locations', 'categories'));
      
      
      
         	
/*          
    	$this->Category->recursive = -1;
    	$categories = $this->Category->find('all', array(
    		'conditions' => array(
    			'Category.parent_id' => 0
    		),
    		'fields' => array(
    			'Category.id',
    			'Category.url_title',
    			'Category.name',
    		),
    		'order' => array(
    			'Category.name ASC'
    		)
    	));  
*/      
      
    	//================================ remove empty categories
    	/*$categoriesWithListings = array();
    	for ($i = 0, $categoriesSize = count($categories); $i < $categoriesSize; $i++) {
    		// init flag that indicates if there are listings
    		$foundListingInCategory = false;

			// first check original category for listings
			$isAnyListings = $this->Category->query("SELECT count(1) AS `counter` FROM `listings` WHERE `category_id` = '".mysql_real_escape_string($categories[$i]["Category"]["id"])."' AND `is_active` = 1", false);
			if ($isAnyListings[0][0]["counter"] > 0) {
				$foundListingInCategory = true;
			}

			// second check category childrens
			if (!$foundListingInCategory) {
				$allDirectChildrens = $this->Category->children($categories[$i]["Category"]["id"], true);
				foreach ($allDirectChildrens as $allDirectChildren) {
					if (!$foundListingInCategory) {
						$isAnyListings = $this->Category->query("SELECT count(1) AS `counter` FROM `listings` WHERE `category_id` = '".mysql_real_escape_string($allDirectChildren["Category"]["id"])."' AND `is_active` = 1", false);
						if ($isAnyListings[0][0]["counter"] > 0) {
							$foundListingInCategory = true;
						}
					}
				}
			}
    		
			// add category if there are any listings in it
			if ($foundListingInCategory) {
				$categoriesWithListings[] = $categories[$i];
			}
    	}
    	unset($categories);
    	$categories = $categoriesWithListings;*/
    	//===============================/ remove empty categories
      
/*
    $this->set('categories', $categories);
    	
    	
		$this->Location->recursive = -1;
    	$locations = $this->Location->find('all', array(
    		'fields' => array(
    			'Location.id',
    			'Location.is_showempty',
    			'Location.url_title',
    			'Location.name',
    		),
    		'order' => array(
    			'Location.name ASC'
    		)
    	));
    	//================================ remove empty categories
    	$locationsWithListings = array();
      $location_ids = array();
    	for ($i = 0, $locationsSize = count($locations); $i < $locationsSize; $i++) {
    		if ($locations[$i]["Location"]["is_showempty"] == 1) {
    			$locationsWithListings[] = $locations[$i]; // show empty locations+categories even if there are no listings in it
          $location_ids[] = $locations[$i]['Location']['id'];
    		} 
        else {
	    		// init flag that indicates if there are listings
	    		$foundListingInLocation = false;
	
				  // check for listings
				  //$isAnyListings = $this->Location->query("SELECT count(1) AS `counter` FROM `listings` WHERE `location_id` = '".mysql_real_escape_string($locations[$i]["Location"]["id"])."' AND `is_active` = 1", false);
          $isAnyListings = $this->Listing->find('count', array('conditions' => array('Listing.location_id' => $location_ids, 'Listing.is_active' => 1)));
				  if ($isAnyListings[0][0]["counter"] > 0) {
					 $foundListingInLocation = true;
				  }
	
				// add category if there are any listings in it
				if ($foundListingInLocation) {
					$locationsWithListings[] = $locations[$i];
				}
    		}
    	}
    	unset($locations);
    	$locations = $locationsWithListings;
    	//===============================/ remove empty categories
    	$this->set('locations', $locations);    
*/    
    }
    
}
?>